from random import randint
from lib.ZImage import ZImage
from lib.ZNode import ZNode
from lib.res.config import win_size
from resource.script.Map.lib.Block import Block
from resource.script.Map.res.glo import _m_src

block_data = {}

class Map ( ZNode ) :
	def __init__ ( self , father ) :
		super ( Map , self ).__init__ ( father )
		self.row = 5
		self.col = 5
		self.blocks = { }
		self._pos = 120 , 100

		self._create_rule ( )
		self.image = ZImage ( self , _m_src [ 'image' ] [ 'background' ] [ randint(0,4) ] , win_size )

	def _create_rule ( self ) :
		self.blocks = self._setblock ( )
		types = self._have_type ( 1 )
		if len ( self._have_item ( types , 0 ) ) > 1 or len ( self._have_item ( types , 1 ) ) > 1 or len (
				self._have_item ( types , 0 ) ) <= 0 or len ( self._have_item ( types , 1 ) ) <= 0 :
			self._create_rule ( )
		global block_data
		block_data = self.blocks

	def _setblock ( self ) :
		blocks = { }
		blockwidth = blockheight = 75
		for x in range ( self.row ) :
			arr = { }
			for y in range ( self.col ) :
				block = Block ( self , x , y , blockwidth , blockheight , status = 0 , type = randint ( 0 , 3 ) )
				block._pos = x * blockwidth , y * blockheight
				arr [ y ] = block
			blocks [ x ] = arr
		blocks [ 4 ] [ 0 ].status = 2
		blocks [ 4 ] [ 0 ].type = 0
		blocks [ 3 ] [ 0 ].status = 1
		blocks [ 4 ] [ 1 ].status = 1
		return blocks

	def _have_type ( self , type ) :
		blocks = [ ]
		for x in self.blocks :
			for y in self.blocks [ x ] :
				if self.blocks [ x ] [ y ].type == type :
					blocks.append ( self.blocks [ x ] [ y ] )
		return blocks

	def _have_item ( self , types , id ) :
		blocks = [ ]
		for x in types :
			if x.item.id == id :
				blocks.append ( x )
		return blocks

	def draw ( self ) :
		self.image.draw ( )
		super ( Map , self ).draw ( )
		if len ( self.blocks ) :
			for x in range ( self.row ) :
				for y in range ( self.col ) :
					self.blocks [ x ] [ y ].draw ( )

	def update ( self , event , pos , key ) :
		if len ( self.blocks ) :
			for x in range ( self.row ) :
				for y in range ( self.col ) :
					self.blocks [ x ] [ y ].update ( event , pos , key )

	def _get_block(self):
		return self.blocks